package com.vmj.classfile.entity.attribute;

import com.vmj.classfile.ClassReader;

/**
 * Created by yangshoujun on 2017/8/6 下午3:35.
 */
public class LineNumberTableAttribute extends AbstractAttribute {

    LineNumberTableEntry[] lineNumberTable;

    public LineNumberTableAttribute(ClassReader classReader) {
        super(classReader);
    }

    public void parse() {
        int lineNumberTableLength = getClassReader().readTwoByte();
        lineNumberTable = new LineNumberTableEntry[lineNumberTableLength];
        for(int i = 0; i < lineNumberTableLength;i++) {
            LineNumberTableEntry entry = new LineNumberTableEntry();
            int startPc = getClassReader().readTwoByte();
            int lineNumber = getClassReader().readTwoByte();
            entry.setStartPc(startPc);
            entry.setLineNumber(lineNumber);
            lineNumberTable[i] = entry;
        }
    }

    public int getLineNumber(int pc) {
        for(int i = (lineNumberTable.length - 1);i >= 0; i--) {
            LineNumberTableEntry entry = lineNumberTable[i];
            if(pc >= entry.getStartPc()) {
                return entry.lineNumber;
            }
        }
        return -1;
    }

    class LineNumberTableEntry {
        int startPc;    //u2
        int lineNumber; //u2

        public int getStartPc() {
            return startPc;
        }

        public int getLineNumber() {
            return lineNumber;
        }

        public void setStartPc(int startPc) {
            this.startPc = startPc;
        }

        public void setLineNumber(int lineNumber) {
            this.lineNumber = lineNumber;
        }
    }

    public LineNumberTableEntry[] getLineNumberTable() {
        return lineNumberTable;
    }

    public void setLineNumberTable(LineNumberTableEntry[] lineNumberTable) {
        this.lineNumberTable = lineNumberTable;
    }
}
